﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wings.Web.Domain;
using NHibernate.Cfg;

namespace Wings.Web
{
    class SessionSetup
    {
        private readonly IPersistenceConfigurer _persistenceConfigurer;
        private SchemaExport _schemaExport;

        public SessionSetup(string connectionString)
        {
            _persistenceConfigurer = MsSqlConfiguration.MsSql2012
                                    .ConnectionString(connectionString)
                                    .AdoNetBatchSize(0);
        }

        public SessionSetup(IPersistenceConfigurer persistenceConfigurer)
        {
            _persistenceConfigurer = persistenceConfigurer;
        }

        public ISessionFactory GetSessionFactory()
        {
            return Fluently.Configure()
                            .Database(_persistenceConfigurer)
				.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Book>()).ExposeConfiguration(CreateSchema)

                            .BuildSessionFactory();
        }

        public void BuildSchema(ISession session)
        {
            _schemaExport.Execute(true, true, false, session.Connection, null);
        }
		private static void CreateSchema(Configuration cfg)
		{
			var schemaExport = new SchemaExport (cfg);

			//schemaExport.SetOutputFile("c:\\abc.sql");
			schemaExport.Create (false, 
				true

			);
		}
    }
}
